#include <stdio.h>
#include <string.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/shm.h>
#define BUFFER_LEN 10

struct Buffer
{
	int value[BUFFER_LEN];
    int producer_index;
    int customer_index;
    int flag;
};

int main(int argc, char const *argv[])
{
    int i;
    void* shm = NULL;

    // 信号量
    sem_t *empty = sem_open("/empty08", O_CREAT, 0666, BUFFER_LEN);

    sem_t *full = sem_open("/full08", O_CREAT, 0666, 0);

    sem_t *mutex = sem_open("/mutex08", O_CREAT, 0666, 1);


    int shmid = shmget(233, 4096, 0666);
    if (shmid == -1)
    {
        fprintf(stderr, "shmat failed\n");
        exit(EXIT_FAILURE);
    }
    
    shm = shmat(shmid, 0, 0);
    if (shm == (void *)-1)
    {
        fprintf(stderr, "shmat failed\n");
        exit(EXIT_FAILURE);
    }
    
    struct Buffer* buffer = (struct Buffer*)shm;

    while (1)
    {
        if (buffer->customer_index == BUFFER_LEN && buffer->flag)
        {
            break;
        }
        sem_wait(full);
        sem_wait(mutex);

        printf("%d: %d\n", 1, buffer->value[buffer->customer_index]);
        buffer->customer_index++;

        sem_post(mutex);
        sem_post(empty);
        sleep(1);
    }

    sem_close(empty);
    sem_close(full);
    sem_close(mutex);
    sem_unlink("/empty08");
    sem_unlink("/full08");
    sem_unlink("/mutex08");

    return 0;
}
